package org.zjx.app.action.task;

import org.zjx.analysis.analyze.game.GameAnalysis;
import org.zjx.analysis.analyze.window.impl.DialogueAnalyzer;
import org.zjx.analysis.analyze.window.impl.ShoppingAnalysis;
import org.zjx.app.action.gather.GatherPropAction;
import org.zjx.app.action.route.BaseRouteAction;
import org.zjx.app.action.window.ClickSceneAction;
import org.zjx.app.action.window.DialogueAction;
import org.zjx.app.action.window.ShoppingAction;
import org.zjx.command.entity.screen.Address;
import org.zjx.command.entity.screen.Npc;
import org.zjx.data.prop.ItemNpcData;
import org.zjx.window.action.Action;
import org.zjx.window.window.IWindow;

import java.awt.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class BuyItemTaskAction extends Action {
    private final String itemName;
    private final int quantity;

    public BuyItemTaskAction(IWindow targetWindow,String itemName, int quantity) {
        super(targetWindow);
        this.itemName = itemName;
        this.quantity = quantity;
    }

    @Override
    protected void doExecute() throws Exception {
        Npc npc = ItemNpcData.findNpcByItem(itemName);
        if (npc == null) throw new Exception("Npc not found");
        GameAnalysis gameAnalysis = new GameAnalysis(targetWindow);
        Address address = gameAnalysis.getAddress();
        if (!npc.getMainLocation().near(address,5)){
            targetWindow.submitAction(new BaseRouteAction(targetWindow,npc.getMainLocation()));
            return;
        }
        ShoppingAnalysis shoppingAnalysis = new  ShoppingAnalysis(targetWindow);
        if (!shoppingAnalysis.isOpened()) {
            DialogueAnalyzer dialogueAnalyzer = new  DialogueAnalyzer(targetWindow);
            if (dialogueAnalyzer.isOpened()){
                targetWindow.submitAction(new DialogueAction(targetWindow, Collections.singletonList("购买")));
            }else {
                List<Point> points = npc.getMovePath();
                List<Address> addressesList = new ArrayList<>();
                for (Point point : points) {
                    addressesList.add(new Address(npc.getSceneName(), point.x, point.y));
                }
                targetWindow.submitAction(new ClickSceneAction(targetWindow, addressesList, ClickSceneAction.ClickType.NPC));
            }
        }else {
            targetWindow.submitAction(new ShoppingAction(targetWindow,itemName,quantity));
            targetWindow.getState().getGameState().setGatherProp(false);
            targetWindow.getState().getGameState().setCommand(null);
            targetWindow.submitAction(new GatherPropAction(targetWindow));
        }
    }
}
